package com.erp.controller;


import com.erp.entity.Loginfo;
import com.erp.entity.Role;
import com.erp.entity.User;
import com.erp.entity.UserRole;
import com.erp.entity.result.Result;
import com.erp.entity.result.ResultStatus;
import com.erp.service.*;
import com.erp.util.SaltUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author pyj
 * @since 2020-11-07
 */
@RestController
@RequestMapping("/user")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private OssService ossService;
    
    @Autowired
    private LoginfoService loginfoService;
    
    @Autowired
    private UserRoleService userRoleService;
    
    @Autowired
    private RoleService roleService;

    // 获取所有用户信息，包括角色，权限
    @GetMapping("/getAllUserInfo")
    public Result getAllUserInfo(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                 @RequestParam(value = "pageSize", required = false, defaultValue = "6") int pageSize) {

        PageHelper.startPage(page,pageSize);
        List<User> userList = userService.getAll();
        // 获取角色
        userList.forEach(user->{
            user.setRoles(userService.findRolesByUserName(user.getUsername()).getRoles());
            user.getRoles().forEach(role -> {
                role.setPerms(userService.findPermsByRoleId(role.getId()));
            });
        });
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        return new Result(ResultStatus.SUCCESS, pageInfo);
    }
    
    @GetMapping("/getUserByPage")
    @RequiresRoles("user")
    public Result getUserByPage(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                   @RequestParam(value = "pageSize", required = false, defaultValue = "8") int pageSize) {

        PageHelper.startPage(page,pageSize);
        List<User> list = userService.getAll();
        PageInfo<User> pageInfo = new PageInfo<>(list);
        return new Result(ResultStatus.SUCCESS, pageInfo);
    }

    @GetMapping("/getUserByUseName")
    public Result getUserByUseName(@RequestParam(value = "username") String username) {
        return new Result(ResultStatus.SUCCESS, userService.findByUserName(username));
    }

    /**
     * 上传头像
     * @param 
     * @return
     */
    @RequestMapping(path = "/uploadHeadPortraits", method = RequestMethod.POST)
        public Result uploadHeader(@RequestParam("file") MultipartFile headerImage) {
        if(headerImage == null) {
            return new Result(ResultStatus.BAD_REQUEST, "你没有选择照片");
        }
        String fileName = headerImage.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if(StringUtils.isBlank(suffix)) {
            return new Result(ResultStatus.BAD_REQUEST, "文件格式不正确");
        }

        // oss
        String headerUrl = ossService.uploadFileAvatar(headerImage);

        //更新当前用户的头像的路径(web访问路径)
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        if (userService.updateHeadPortraits(username, headerUrl) > 0) {
            return new Result(ResultStatus.SUCCESS, "修改成功");
        } else {
            return new Result(ResultStatus.BAD_REQUEST, "修改失败");
        }
    }
    
    @PostMapping("/add")
    @RequiresRoles("admin")
    public Result insert(@PathParam("username") String username, @PathParam("password") String password,
                         @PathParam("roles") String roles, @RequestParam("file") MultipartFile headerImage) {
        String fileName = headerImage.getOriginalFilename();
        User user = new User();
        user.setUsername(username);
        String salt = SaltUtils.getSalt(6);
        user.setPassword(SaltUtils.shiroMd5(password, salt));
        user.setSalt(salt);
        String headerUrl;
        if(headerImage == null) {
            // 设置默认头像
            user.setHeadurl("https://vue-erp.oss-cn-guangzhou.aliyuncs.com/head/head.png");
        } else {
            // oss
            headerUrl = ossService.uploadFileAvatar(headerImage);
            user.setHeadurl(headerUrl);
        }
        if (userService.add(user) > 0) {
            String[] res = roles.split(",");
            for (String s : res) {
                Role role = roleService.findRoleByName(s);
                UserRole userRole = new UserRole();
                userRole.setRid(role.getId());
                userRole.setUid(user.getId());
                userRoleService.add(userRole);
            }
            return new Result(ResultStatus.SUCCESS, null);
        } else {
            return new Result(ResultStatus.BAD_REQUEST, null);
        }
       
    }
    
    @GetMapping("/login")
    public Result login(@PathParam("username") String username, @PathParam("password") String password, HttpServletRequest request) {

        Subject subject  = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
            Loginfo loginfo = new Loginfo();
            loginfo.setLoginName(username);
            loginfo.setCreateTime(new Date());
            loginfo.setLoginIp(request.getRemoteAddr());
            loginfoService.add(loginfo);
        } catch (UnknownAccountException e) {
            System.out.println("用户名错误");
            return new Result(ResultStatus.BAD_REQUEST, "用户名错误");
        } catch (IncorrectCredentialsException e) {
            System.out.println("密码错误");
            return new Result(ResultStatus.BAD_REQUEST, "密码错误");
        }
        
        return new Result(ResultStatus.SUCCESS, "登陆成功");
        
    }
    
    
    @PostMapping("/update")
    public Result update(@PathParam("id") String id, @PathParam("username") String username, @PathParam("oldPassword") String oldPassword, @PathParam("newPassword") String newPassword,
                         @PathParam("name") String name, @PathParam("sex") String sex, @PathParam("phone") String phone, @PathParam("address") String address,
                         @PathParam("roles") String roles, @RequestParam("file") MultipartFile headerImage) {

        User user = userService.findByUserId(id);
        if (user.getPassword().equals(SaltUtils.shiroMd5(oldPassword, user.getSalt()))) {
            // 旧密码符合，修改新密码
            user.setUsername(username);
            user.setPassword(SaltUtils.shiroMd5(newPassword, user.getSalt()));
            if (headerImage != null) {
                // oss
                String headerUrl = ossService.uploadFileAvatar(headerImage);
                user.setHeadurl(headerUrl);
            }
            user.setName(name);
            user.setSex(sex);
            user.setPhone(phone);
            user.setAddress(address);
            if (userService.update(user, roles) > 0) {
                return new Result(ResultStatus.SUCCESS, "修改成功");
            } else {
                return new Result(ResultStatus.BAD_REQUEST, "修改失败");
            }
        } else {
            return new Result(ResultStatus.BAD_REQUEST, "密码错误");
        }
    }

    @GetMapping("/delete")
    @RequiresRoles("admin")
    public Result delete(@PathParam("id") Integer id) {
        if (userService.delete(id) > 0) {
            return new Result(ResultStatus.SUCCESS, null);
        } else {
            return new Result(ResultStatus.BAD_REQUEST, null);
        }
    }

    
}

